package com.ruowei.modules.sys.utils;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.stream.FileImageOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

public class FileUploadUtils {

    public static boolean picTOSize(byte[] oldPath, String newPath) {
        if (oldPath.length <= 204800) return false; //文件低于200kb 不转换
        //图片数组

        byte[] bytes1 = compressPicForScale(oldPath);//图片控制到180kb~130kb之间

        FileImageOutputStream imageOutput = null;
        try {

            File file = new File(newPath);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            file.createNewFile();
            imageOutput = new FileImageOutputStream(file);
            imageOutput.write(bytes1, 0, bytes1.length);
            imageOutput.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    private static byte[] compressPicForScale(byte[] imageBytes) {
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < (long) 190 * 1024) {
            return imageBytes;
        }
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
        try {
            while (imageBytes.length > (long) 190 * 1024) {
                ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
                Thumbnails.of(inputStream)
                    .scale(accuracy)
                    .outputQuality(accuracy)
                    .toOutputStream(outputStream);
                imageBytes = outputStream.toByteArray();
            }
            //("【图片压缩】imageId={} | 图片原大小={}kb | 压缩后大小={}kb",
            //   imageId, srcSize / 1024, imageBytes.length / 1024);
        } catch (Exception e) {
            //("【图片压缩】msg=图片压缩失败!", e);
        }
        return imageBytes;
    }

    private static double getAccuracy(long size) {
        double accuracy;
        if (size < 900) {
            accuracy = 0.88;
        } else if (size < 2047) {
            accuracy = 0.67;
        } else if (size < 3275) {
            accuracy = 0.44;
        } else {
            accuracy = 0.4;
        }
        return accuracy;
    }
}
